// pages/lianx/lianx.js
const common = require('../../../public.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isOverShare: true,  //全局分享标识请勿删除
        showGong: true, //攻略是否展开
        toitem: "",
        storeId: 397,
        currentBanner: 1, //轮播数字
        cateIndex: -1,
        showGoodsLimit: '10',
        showLimit: 10,
        articleList: [], //总
        articleLists: [],
        pageNum: 1,
        isCollected: '', //是否收藏
        storeCouponsList: [], //店铺优惠券列表
        showStoreCoupons: false,
        canLoad: true,
        isLoadingBusy: false,
    },
    //  去详情页
    toDetail(e) {
        console.log(e.currentTarget.dataset.item, "jjjjooooo")
        let item = JSON.stringify(e.currentTarget.dataset.item)
        if (item.couponType == 1) {  //线上详情
            wx.navigateTo({
                url: '/pages/coupons/useCoupons/index?&from=company' + '&item=' + item,
            })
        }else{
            wx.navigateTo({
                url: '/pages/coupons/useCouponsTwo/index?&from=company' + '&item=' + item,
            })
        }
    },
    // 领券弹框
    to_coupfn() { this.setData({ showStoreCoupons: true }) },
    onStoreCouponosClose() { this.setData({ showStoreCoupons: false }) },
    toArticleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/discovery/articleDetail/index?id=' + item.id +
                '&storeName=' + item.storeName +
                '&title=' + item.title +
                '&createTime=' + item.createTime +
                '&storeImg=' + item.storeImg
        })
    },

    receiveStoreConpons(e) {
        var that = this;
                   var   id1 = '0BBIhQnR7-gWMckj1igwk0Q29dsDyXWTlsZ3SD0xFGc';
                   var   id2 = 'iyLKpuYyzFibbG56DazRpXBK60FJ0HH5iQJKAdbjWXk';
        wx.requestSubscribeMessage({
            //  0BBIhQnR7-gWMckj1igwk0Q29dsDyXWTlsZ3SD0xFGc优惠券到账
            // iyLKpuYyzFibbG56DazRpXBK60FJ0HH5iQJKAdbjWXk 优惠券过期 
            // 调起消息订阅界面
            tmplIds: [id1,id2],
            success(res) {
                console.log('xx订阅消息 成功 ');
                console.log(res)
            },
            fail(er) {
                console.log("xx订阅消息 失败 ");
                console.log(er)
            },
                   
                   

            complete: (errMsg) => {
                console.log("xx数据",errMsg)
                that.receiveAPi(e);
                
            }
        })


    
    },
    receiveAPi(e){
        let that = this
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }
        common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
                that.setData({
                    storeCouponsList: []
                }, () => {
                    that.getStoreCoupons(that.data.storeId, true)
                })

            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },
    // 列表触底
    loadMore() {
        this.getStoreCoupons(false)
    },
    // 店铺优惠券列表
    getStoreCoupons(refresh = true) {
        const that = this
        if (refresh) {
            this.data.canLoad = true
        }
        if (that.data.canLoad) {  //可以加载
            if (!refresh && this.data.isLoadingBusy) {
                return
            }
            this.setData({
                isLoadingBusy: true
            })
            const params = {
                storeId: that.data.storeId,
                pageNum: refresh ? 1 : that.data.pageNum + 1,
                status: 4
            }
            common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
                if (res.status === 200) {
                    that.data.pageNum = params.pageNum
                    if (res.data.result_list != '' || res.data.result_list.length != 0) {
                        that.setData({
                            storeCouponsList: [...that.data.storeCouponsList, ...res.data.result_list],
                        })
                    } else {
                        if (that.data.pageNum == 1) {
                            that.setData({
                                storeCouponsList: []
                            })
                            return
                        }
                        that.setData({
                            canLoad: false,
                        })
                    }

                }
            }, function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
        }

    },
    //   收藏店铺
    clickCollect() {
        let that = this
        wx.getStorage({ //获取本地缓存
            key: 'user',
            success(res) {
                that.setData({
                    userInfo: res.data.user,
                    openid: res.data.openid,
                    token: res.data.token
                }, () => {
                    // isCollected是关注，非isCollected是未关注
                    let param = that.data.isCollected ? 'delete' : 'add'
                    var temp = {
                        token: that.data.token,
                        userId: that.data.userInfo.id,
                        storeId: that.data.storeId
                    };
                    common.post("/store/favo/" + param, temp, function (res) {
                        res.status == 200 && that.queryCollection() //刷新一下接口，刷新状态
                    })
                })
            }
        })
    },
    // 获取是否收藏的状态
    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                // false是未关注
                isCollected: res.data
            })
        });
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 地图导航
    checkAddress() { //点击地址按钮
        if (!this.data.storeInfo.store.xpoint || !this.data.storeInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.storeInfo.store.xpoint)
        let lat = parseFloat(this.data.storeInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.storeInfo.store.name ? this.data.storeInfo.store.name : null,
            address: this.data.storeInfo.store.address ? this.data.storeInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 攻略展开更多
    showMore() {
        console.log("看的到")
        this.gong(false)
    },
    guanMore() {
        this.gong(true)
    },
    gong(refresh = false) {
        const that = this
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        let tempJson = {
            pageSize: 10,
            pageNum,
            storeId: this.data.storeId
        }
        common.post('/storeArticle/getStoreArticleListForOneStore', tempJson,
            function (res) {
                if (res.status === 200) {
                    that.setData({
                        articleList: res.data,
                        articleLists: refresh ? res.data.list : [...res.data.list, ...that.data.articleLists]
                    })
                } else {
                    // common.showRequestErrMsg(res)
                }
            },
            function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
    },
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.storeInfo.store.mobile,
            fail: function () { }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, "options")
        // 飞羊小程序显示的是页面，展示返回按钮
        const capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
            storeId: options.id ? options.id : 5042
        }, () => {
            const that = this
            common.getLocalUserInfo(function (success, data) {
                if (success) {
                    that.setData({
                        userInfo: data.user,
                        token: data.token,
                        openid: data.openid,

                    })
                    that.getInfo()
                    that.gong(true)
                    that.queryCollection()
                    that.getStoreCoupons(that.data.storeId, true)
                }
            }, true)

        })
    },
    // 收起
    hidess() {
        this.setData({
            showGoodsLimit: 10,
        })
    },
    // 点击查看更多
    showMoreGoods() { // 查看更多商品
        this.setData({
            showGoodsLimit: this.data.storeInfo.itemCount
        })
    },
    // 切换分类
    categoryClick(e) {
        const idx = e.currentTarget.dataset.id;
        const index = e.currentTarget.dataset.index;
        if (this.data.cateIndex === index) {
            return
        }
        const that = this
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    cateIndex: index
                })
                that.changeCategory(idx)
            }
        }, true)
    },
    changeCategory(idx) {
        this.setData({
            isLoading: true
        })
        const that = this
        const tempJson = {
            // cid: idx,
            storeCid: idx,
            storeId: that.data.storeId,
            // storeId:2182,
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        // common.post('/store/mainPageInfo/cid', tempJson, function (res) {storeCid
        common.post('/store/mainPageInfo/storeCid', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    defaultItemList: res.data.data
                })
            } else {
                that.setData({
                    defaultItemList: []
                })
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    toTeamDetail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/packageA/pages/Goods/teamStyle/teamDetail/index?teamId=' + id,
        })
    },
    goodsDetail(e) {
     
        common.gotoGoodsPage(e.currentTarget.dataset.item)
    },
    bannerChange(e) { // 轮播滚动触发
        let {
            current
        } = e.detail
        this.setData({
            currentBanner: current + 1
        })
    },
    seeAllEvaluateClick() { // 查看更多评论
        this.setData({
            showLimit: this.data.mainPageInfo.commentCount
        })
    },
    hideEvaluate() {
        this.setData({
            showLimit: 10
        })
    },
    // 团队风采更多
    toTeamStyle() {
        wx.navigateTo({
            url: '/packageA/pages/Goods/teamStyle/index?storeId=' + this.data.storeId,
        })
    },
    // 客户见证
    toWitness() {
        wx.navigateTo({
            url: '/packageA/pages/Goods/witness/index?storeId=' + this.data.storeId,
        })
    },
    // 获取详情
    getInfo() {
        const that = this
        const tempJson = {
            storeId: that.data.storeId
            // storeId:1641
        }
        common.post('/store/mainPageInfo', tempJson,
            function (res) {
                if (res.status === 200) {
                    console.log(res);

                    that.setData({
                        storeInfo: res.data,
                        commentList: res.data.commentList,
                        storeCatList: res.data.itemCatList2.storeCatList,
                        defaultItemList: res.data.itemCatList2.defaultItemList,
                        isFyApp: false
                    })
                    if (that.data.moduleType == 2) { // 文化场馆
                        that.setData({
                            articleList: res.data.articleList
                        })
                    }
                } else {
                    common.showRequestErrMsg(res)
                }
            },
            function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
    },
    goCustem(e) {
        //     var me = this;
        //   var query = wx.createSelectorQuery().in(me);
        //   query.selectViewport().scrollOffset()
        //   query.select("#comment").boundingClientRect();
        //   query.exec(function (res) {
        //     console.log(res);
        //     var miss = res[0].scrollTop + res[1].top - 10;
        //     console.log(miss)
        //     wx.pageScrollTo({
        //       scrollTop: miss,
        //       duration: 300
        //     });

        //   });
        console.log(e)
        let option = e.currentTarget.dataset.item;
        this.setData({
            toitem: option
        })

    },
    goteam(e) {
        let option = e.currentTarget.dataset.item;
        this.setData({
            toitem: option
        })
    },
    goGongLue(e) {
        let option = e.currentTarget.dataset.item;
        this.setData({
            toitem: option
        })
    },
    goevaluate(e) {
        let option = e.currentTarget.dataset.item;
        this.setData({
            toitem: option
        })
    },
    showStorePage() {

        const pages = getCurrentPages()
        wx.redirectTo({
            url: '/pages/index/index',
        })
    },
    //   onShareAppMessage: function () {
    //     return {
    //       title: this.data.mainPageInfo.store.name,
    //       path: '/packageA/pages/Goods/storePage/index?id=' + this.data.storeId,
    //       imageUrl: '',
    //       success: (res) => {
    //         // 分享成功
    //       },
    //       fail: (res) => {
    //         // 分享失败
    //       }

    //     }
    //   },
    onShareAppMessage: function () {
        return {
            title: '飞羊精选',
            path: '/packageA/pages/Goods/storePage/index?id=' + this.data.storeId,
            imageUrl: '',

            success: (res) => { },
            fail: (res) => {
                // 分享失败
            }
        }
    },
    //   onShareTimeline() {
    //     return {
    //       title: this.data.storeName,
    //       query: 'id=' + this.data.storeId,
    //       imageUrl: this.data.storeImage
    //     }
    //   }
})